package com.ruoyi.websocket.service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.websocket.WebSocketEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

@Component
public class WebSocketService {

    public void sendMessageToAll(JSONObject payload) {
        try {
            Objects.requireNonNull(payload, "未指定发送的消息内容");
            WebSocketEndpoint.sendMessageToAll(payload.toJSONString());
        } catch (IOException e) {
            log.error("发送消息给用户连接错误", e);
        }
    }

    public void sendMessageByUserId(Long userId, JSONObject payload) {
        try {
            Objects.requireNonNull(userId, "未指定发送的用户");
            Objects.requireNonNull(payload, "未指定发送的消息内容");
            WebSocketEndpoint.sendMessageToUser(userId, payload.toJSONString());
        } catch (IOException e) {
            log.error("发送消息给用户连接错误", e);
        }
    }
}
